const AutoLoad = require("fastify-autoload");
const path = require("path");
// 加载框架并新建实例
const fastify = require("fastify")({
  logger: true,
  ignoreTrailingSlash: true,
});
// const hooks = require("./addhook");
fastify.register(require("./our-first-route"));
fastify.register(require("./userApi"));
fastify.register(AutoLoad, {
  dir: path.join(__dirname, "models"),
});
fastify.register(AutoLoad, {
  dir: path.join(__dirname, "routes"),
});
fastify.register(AutoLoad, {
  dir: path.join(__dirname, "sequelize"),
});
// hooks(fastify);
fastify.register(require("fastify-cors"), function (instance) {
  return (req, callback) => {
    let corsOptions;
    const origin = req.headers.origin;
    req.headers["Access-Control-Allow-Origin"] = "http://localhost:9528";
    // do not include CORS headers for requests from localhost
    if (/localhost/.test(origin)) {
      corsOptions = { origin: true };
    } else {
      corsOptions = { origin: true };
    }
    callback(null, corsOptions); // callback expects two parameters: error and options
  };
});

// 启动服务！
fastify.listen(3000, function (err, address) {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
  fastify.log.info(`server listening on ${address}`);
});
